package com.wit.dao.impl;

import hibernate.HibernateSessionFactory;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.wit.dao.ProjectDao;
import com.wit.po.Insurancedef;
import com.wit.po.Project;

public class ProjectDaoImpl implements ProjectDao {

	
	public boolean addProject(Project project) {
		Session s = null;
		Transaction tx = null;
		boolean isFinished = false;
		try{
			s = HibernateSessionFactory.getSession();
			tx =  s.beginTransaction();
			s.save(project);
			tx.commit();
			s.close();
			isFinished = true;
		}catch(HibernateException e){
			tx.rollback();
			e.printStackTrace();
		}finally{
			if(s.isOpen())
				s.close();
		}
		return isFinished;
	}

	
	public boolean deleteProject(Project project) {
		Session s = null;
		Transaction tx = null;
		boolean isFinished = false;
		try{
			s = HibernateSessionFactory.getSession();
			tx =  s.beginTransaction();
			s.delete(project);
			tx.commit();
			s.close();
			isFinished = true;
		}catch(HibernateException e){
			tx.rollback();
			e.printStackTrace();
		}finally{
			if(s.isOpen())
				s.close();
		}
		return isFinished;
	}

	
	public Project findProjectByIdenfier(String projectNum) {
		Session s = null;
		Project project = null;
		try{
			s = HibernateSessionFactory.getSession();
			List<Project> compList = (List<Project>)s.createQuery("FROM Project WHERE projectNum = ?").setString(0, projectNum).list();
			if(compList.size() == 1)
				project = compList.get(0);
			s.close();
		}catch(HibernateException e){
			e.printStackTrace();
		}finally{
			if(s.isOpen())
				s.close();
		}
		return project;
	}

	
	public List<Project> findProjectByInsurancedef(Insurancedef insurancedef) {
		Session s = null;
		List<Project> projectList = new ArrayList<Project>();
		try{
			s = HibernateSessionFactory.getSession();
			projectList = (List<Project>)s.createQuery("FROM Project WHERE insurancedef = ?").setParameter(0, insurancedef).list();
			s.close();
		}catch(HibernateException e){
			e.printStackTrace();
		}finally{
			if(s.isOpen())
				s.close();
		}
		return projectList;
	}

	
	public boolean modifyProject(Project project) {
		Session s = null;
		Transaction tx = null;
		boolean isFinished = false;
		try{
			s = HibernateSessionFactory.getSession();
			tx =  s.beginTransaction();
			s.update(project);
			tx.commit();
			s.close();
			isFinished = true;
		}catch(HibernateException e){
			tx.rollback();
			e.printStackTrace();
		}finally{
			if(s.isOpen())
				s.close();
		}
		return isFinished;
	}

}
